package com.heima.behavior.service.impl;

import com.heima.behavior.dto.ArticleBehaviorDto;
import com.heima.behavior.service.ApBehaviorServcie;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.entity.ApUser;
import com.heima.user.util.AppThreadLocalUtil;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

public class ApBehaviorServcieImpl implements ApBehaviorServcie {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ResponseResult loadArticleBehavior(ArticleBehaviorDto dto) {
        //1.检查参数
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2.查询行为实体
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.okResult(new HashMap<>());
        }

        boolean isUnlike = false,isLike = false,isCollection = false,isFollow = false;

        //3.查询收藏行为
        String collection_hash_key  = "USER_COLLECTION_" + dto.getArticleId();
        isCollection = stringRedisTemplate.opsForHash().hasKey(collection_hash_key, user.getId() + "");

        //4.查询点赞行为
        String like_hash_key = "USER_LIKES_" + dto.getArticleId();
        isLike = stringRedisTemplate.opsForHash().hasKey(like_hash_key, user.getId() + "");

        //5.查询关注行为
        String follow_hash_key  = "USER_FOLLOW_" + user.getId();
        isFollow = stringRedisTemplate.opsForHash().hasKey(follow_hash_key,dto.getAuthorId() + "");

        //6.查询不喜欢行为
        String unlike_hash_key = "USER_UNLIKES_" + dto.getArticleId();
        isUnlike = stringRedisTemplate.opsForHash().hasKey(unlike_hash_key,user.getId() + "");

        //7.结果返回
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("isfollow",isFollow);
        resultMap.put("islike",isLike);
        resultMap.put("isunlike",isUnlike);
        resultMap.put("iscollection",isCollection);

        return ResponseResult.okResult(resultMap);
    }
}
